import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { MiniDB, RemoteDB } from '@lazycatcloud/minidb'
import { getUid } from '@/utils/getUid'
import { displayOrder } from '@/config'

export const useAssistantListStore = defineStore('assistantList', () => {
  const completedAssistantList = ref<string[]>([])
  const db = new MiniDB()
  const state: RemoteDB<{
    key: string
    list: string[]
  }> = db.getCollection('AssistantList')

  const getCompletedAssistantList = async () => {
    const uid = await getUid()
    if (!uid) return
    const _state = await state.findOne({
      key: uid,
    })

    completedAssistantList.value = _state?.list || []
  }

  const updateCompletedAssistantList = async (id: string) => {
    const uid = await getUid()
    if (!uid) return
    const index = completedAssistantList.value.findIndex((t) => t == id)
    if (index !== -1) return
    completedAssistantList.value.push(id)
    state.upsertOrUpdate(
      { key: uid },
      {
        key: uid,
        list: completedAssistantList.value,
      },
    )
  }

  const completedList = computed(() => {
    return displayOrder.filter((item) => {
      return completedAssistantList.value.includes(item)
    })
  })

  const allCompleted = computed(() => {
    return displayOrder.length == completedList.value.length
  })

  const clear = async () => {
    const uid = await getUid()
    if (!uid) return
    completedAssistantList.value = []
    state.upsertOrUpdate(
      { key: uid },
      {
        key: uid,
        list: [],
      },
    )
  }

  const readAll = async () => {
    const uid = await getUid()
    if (!uid) return
    completedAssistantList.value = displayOrder
    state.upsertOrUpdate(
      { key: uid },
      {
        key: uid,
        list: displayOrder,
      },
    )
  }

  (window as any).lzc_clear = clear

  return {
    getCompletedAssistantList,
    updateCompletedAssistantList,
    completedList,
    allCompleted,
    clear,
    readAll
  }
})
